package com.biostime.qdingding.modules.qd.api;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.biostime.qdingding.common.api.FastResponse;
import com.biostime.qdingding.common.api.ObjResponse;
import com.biostime.qdingding.common.web.BaseController;
import com.biostime.qdingding.modules.qd.api.dto.BalanceDto;
import com.biostime.qdingding.modules.qd.api.dto.ContractDto;
import com.biostime.qdingding.modules.qd.api.dto.DiscountDto;
import com.biostime.qdingding.modules.qd.api.dto.MyAccountDto;
import com.biostime.qdingding.modules.qd.api.dto.PersonalCenterDto;
import com.biostime.qdingding.modules.qd.api.dto.TransrecordDto;
import com.biostime.qdingding.modules.qd.api.dto.UploadResultDto;
import com.biostime.qdingding.modules.qd.entity.Album;
import com.biostime.qdingding.modules.qd.entity.CourseOrder;
import com.biostime.qdingding.modules.qd.entity.Member;
import com.biostime.qdingding.modules.qd.entity.Privilege;
import com.biostime.qdingding.modules.qd.entity.Promotion;
import com.biostime.qdingding.modules.qd.entity.Student;
import com.biostime.qdingding.modules.qd.service.AlbumService;
import com.biostime.qdingding.modules.qd.service.BookConfirmService;
import com.biostime.qdingding.modules.qd.service.ContractService;
import com.biostime.qdingding.modules.qd.service.CourseOrderService;
import com.biostime.qdingding.modules.qd.service.MemberService;
import com.biostime.qdingding.modules.qd.service.PriceService;
import com.biostime.qdingding.modules.qd.service.PrivilegeService;
import com.biostime.qdingding.modules.qd.service.PromotionService;
import com.biostime.qdingding.modules.qd.service.StudentService;
import com.biostime.qdingding.modules.qd.service.TransrecordService;
import com.biostime.qdingding.modules.sys.entity.Area;
import com.biostime.qdingding.modules.sys.entity.User;
import com.biostime.qdingding.modules.sys.service.AreaService;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;

/**
 * 我的App
 * 
 * @author chenweicheng
 * @version 2015-11-06
 */
@RestController
@RequestMapping(value = "${adminPath}/qd/api/myApp")
public class MyAppApi extends BaseController {
	
	public static Logger logger=Logger.getLogger("api"); 

	@Autowired
	private MemberService memberService;

	@Autowired
	private ContractService contractService;

	@Autowired
	private TransrecordService recordService;

	@Autowired
	private PromotionService promotionService;

	@Autowired
	private AlbumService albumService;

	@Autowired
	private AreaService areaService;
	
	@Autowired
	private StudentService studentService;
	
	@Autowired
	private BookConfirmService bookConfirmService;
	
	@Autowired
	private PriceService priceService;
	
	@Autowired
	private CourseOrderService courseOrderService;
	
	@Autowired
	private PrivilegeService privilegeService;

	/**
	 * 个人中心/获取我的信息
	 * 
	 * @param userId
	 * @return
	 */
	@RequestMapping(value = "personalCenter")
	public ObjResponse<PersonalCenterDto> personalCenter(String userId, String studentId) {
		PersonalCenterDto person = null;
		int errcode = 0, subcode = 0;
		String message = null;

		if ((userId != null && !userId.equals("") && studentId != null && !studentId.equals(""))) {
			person = memberService.apiGet(userId);
			if (person != null) {
				Student student = new Student();
				student.setId(studentId);
				person.setMessageCount(99);
				BalanceDto balance = recordService.getBalance(student);
				if (balance != null)
					person.setBalance(priceService.changeMoney(balance.getSumPay() - balance.getSumCost() - balance.getSumFreeze()));
				
				// 获取优惠列表
				List<HashMap<String, Object>> promotionIdMap = promotionService.apiGetIdByStudent(studentId);
				List<DiscountDto> discountDtoList = new ArrayList<DiscountDto>();			
				if (promotionIdMap != null) {
					Promotion promotion = null;
					DiscountDto discountDto = null;
					for (int i = 0; i < promotionIdMap.size(); i++) {
						if (promotionIdMap.get(i).get("PROMOTIONID") != null) {
							BigDecimal id = (BigDecimal) promotionIdMap.get(i).get("PROMOTIONID");
							promotion = promotionService.get(String.valueOf(id));
							discountDto = new DiscountDto();
							discountDto.setId(Integer.parseInt(promotion.getId()));
							discountDto.setName(promotion.getName());
							discountDto.setDescription(promotion.getRemarks());
							discountDtoList.add(discountDto);
						}
					}
				}
				person.setDiscountList(discountDtoList);
				
				if(!discountDtoList.isEmpty()){
					if(!studentId.equals(String.valueOf(BasicApi.defaultStudentId))){
						person.setLevel(studentService.getStudentLevel(Integer.parseInt(studentId)));	
					}
				}
				message = "获取个人中心信息详情成功";
			} else {
				errcode = 1;
				message = "获取宝宝信息失败";
			}
		} else {
			errcode = 1;
			message = "获取个人中心信息详情失败,参数有误";
		}
		return FastResponse.create().errCode(errcode).subCode(subcode).errMsg(message).obj(person);
	}

	/**
	 * 我的账户/获取我的账户信息
	 * 
	 * @param userId
	 * @return
	 */
	@RequestMapping(value = "myAccount")
	public ObjResponse<MyAccountDto> myAccount(HttpServletRequest request) {
		
		//默认页数为1，条数为10
		int pageindex = 1;
		int pagesize = 10;
		String studentId = request.getParameter("studentId");		
		if(request.getParameter("pageindex") !=null && !request.getParameter("pageindex").equals("")
				&& request.getParameter("pagesize") != null && !request.getParameter("pagesize").equals("")){
			pageindex = Integer.parseInt(request.getParameter("pageindex"));
			pagesize = Integer.parseInt(request.getParameter("pagesize"));
		}
		
		//获取合同列表
		Student student=new Student();
		student.setId(studentId);
		List<ContractDto> listContract=contractService.apiGetContract(studentId);
		BalanceDto balance = recordService.getBalance(student);

		//分页操作
		PageHelper.startPage(pageindex, pagesize);
		List<TransrecordDto> transrecordList=recordService.apiGetTransrecords(studentId);
				
		//上课的总费用,上课总数		
		double sum = 0;
		List<CourseOrder>  courseOrderList= courseOrderService.apiGetByStudent(studentId, "signed");
		if(transrecordList!=null && !transrecordList.isEmpty() && courseOrderList != null && !courseOrderList.isEmpty())
			for(CourseOrder order :courseOrderList){
				for(TransrecordDto td:transrecordList){
				if(td.getInout()==1){	
					if(td.getCourseorderId().equals(order.getId())){
						sum+=td.getInvolveMoney();
					}					
					
				}
			}
		}
					
		//设置余额，冻结金额，合同有效期
		MyAccountDto myAccount = new MyAccountDto();				
		if (balance != null) {
			
			//账户余额，余额不保留小数
			Double balance2 = balance.getSumPay() - balance.getSumCost() - balance.getSumFreeze();
			BigDecimal b = new BigDecimal(balance2);  
			double changeAfter = b.setScale(1,BigDecimal.ROUND_HALF_UP).doubleValue();  
			myAccount.setBalance(changeAfter);
			myAccount.setFrozenBalance(priceService.changeMoney(balance.getSumFreeze()));
			myAccount.setLimitDate(balance.getLimitDate());
		
			//如果支付的钱小于合同的钱
			if(listContract != null && !listContract.isEmpty()){
				if(balance.getSumPay() <listContract.get(0).getAmount() ){
					myAccount.setAvailable(true); 			
				}				
			}
			
		}else{
			if(myAccount.getLimitDate() == null){
				if(listContract != null && !listContract.isEmpty()){
					myAccount.setLimitDate(listContract.get(0).getEndDate()); 
				}
			}			
		}
		
		//如果合同有效期已到，或者合同被中止
		if(listContract != null && !listContract.isEmpty()){
			if(listContract.get(0).getEndDate().getTime() <= new Date().getTime()){
				myAccount.setAvailable(false); 	
			}
			if(listContract.get(0).getAbort() == 1){
				myAccount.setAvailable(false); 
			}
		}
				
		//上了多少节课
		myAccount.setCourseCount(courseOrderList.size());
		
		//平均价格
		if(!courseOrderList.isEmpty()){
			myAccount.setAvgPrice(priceService.changeMoney(sum / courseOrderList.size()));			
		}else{
			myAccount.setAvgPrice(0d);
		}
		
		//合同
		if(listContract != null && !listContract.isEmpty()){
			
			//截取合同编号
			for(int i =0 ;i<listContract.size() ;i++){
				if(listContract.get(i).getCode().length() > 14){
					listContract.get(i).setCode(listContract.get(i).getCode().substring(0, 13));   
				}
			}
		}
		myAccount.setContracts(listContract);	
				
		//历史合同
		List<ContractDto> historyContract=contractService.apiGetHistoryContracts(studentId);
		if(historyContract != null && !historyContract.isEmpty()){
			
			//截取合同编号
			for(int i =0 ;i<historyContract.size() ;i++){
				if(listContract.get(i).getCode().length() > 14){
					historyContract.get(i).setCode(historyContract.get(i).getCode().substring(0, 13));   
				}
			}
		}		
		myAccount.setHistoryContracts(historyContract);
		
		//收支记录
		if(transrecordList != null && !transrecordList.isEmpty()){
			for(int i=0;i<transrecordList.size();i++){
				double money = transrecordList.get(i).getInvolveMoney();
				transrecordList.get(i).setInvolveMoney(priceService.changeMoney(money));
			}
		}
		myAccount.setTransrecoreds(transrecordList);
		
		if(listContract!=null && listContract.size()>0){
			myAccount.setTips(bookConfirmService.getContractFeeStatus(studentId).getTips());
		}
		
		return FastResponse.create().errMsg("").errCode(0).subCode(0).obj(myAccount);
		
	}
	
	/**
	 * 获取合同需要支付金额
	 * @param userId
	 * @param studentId
	 * @return
	 */
	@RequestMapping(value = "getNeedPay")
	public ObjResponse<Object> getNeedPay(String userId,String studentId){
		String message = null;
		int errCode = 1;
		double needPay = 0d;
		
		if(userId != null && !userId.equals("") && studentId != null && !studentId.equals("")){
			
			//获取合同列表
			Student student=new Student();
			student.setId(studentId);
			List<ContractDto> listContract=contractService.apiGetContract(studentId);
			
			if(listContract != null && !listContract.isEmpty()){
				double amount = listContract.get(0).getAmount();
				double pay = recordService.apiGetRecharge(studentId,String.valueOf(listContract.get(0).getId()));
				needPay = amount - pay;
			}
			
			errCode = 0;
			message = "获取成功";
		}else{
			message = "获取失败，参数不全";
		}

		
		return FastResponse.create().errCode(errCode).errMsg(message).obj(needPay);		
	}
	
	/**
	 * 优惠特权/获取我的优惠信息
	 * 
	 * @param userId
	 * @return
	 */
	@RequestMapping(value = "myDiscount")
	public ObjResponse<HashMap<String,Object>> myDiscount(String userId, String studentId) {
		
		List<HashMap<String, Object>> promotionIdMap = promotionService.apiGetIdByStudent(studentId);
		List<DiscountDto> discountDtoList = new ArrayList<DiscountDto>();
		if (promotionIdMap != null) {
			Promotion promotion = null;
			DiscountDto discountDto = null;
			for (int i = 0; i < promotionIdMap.size(); i++) {
				if (promotionIdMap.get(i).get("PROMOTIONID") != null) {
					BigDecimal id = (BigDecimal) promotionIdMap.get(i).get("PROMOTIONID");
					promotion = promotionService.get(String.valueOf(id));
					discountDto = new DiscountDto();
					discountDto.setId(Integer.parseInt(promotion.getId()));
					discountDto.setName(promotion.getName());
					if(i==0)discountDto.setDescription(studentService.getStudentLevel(Integer.parseInt(studentId)));
					discountDtoList.add(discountDto);
				}
			}
		}
		
		//优惠列表
		HashMap<String,Object>  hashMap = new HashMap<String,Object>();
		hashMap.put("discountDtoList", discountDtoList);
		int leavePrivilege = 0;
		int cancelPrivilege = 0;
		Privilege p1 = null;
		Privilege p2 = null;
		
		//学员合同
		List<ContractDto> contractList = contractService.apiGetContract(studentId);
		if(contractList != null && !contractList.isEmpty()){
			String contractId = String.valueOf(contractList.get(0).getId());
			p1 = privilegeService.apiGetPrivilege("leave", contractId);
			p2 = privilegeService.apiGetPrivilege("abort", contractId);			
		}
		
		//请假资格
		if(p1 != null ){
			leavePrivilege = p1.getTotal()-p1.getUsed();
		}
		
		//取消资格
		if(p2 != null){
			cancelPrivilege = p1.getTotal()-p1.getUsed();
		}
		
		hashMap.put("leavePrivilege", leavePrivilege);
		hashMap.put("cancelPrivilege", cancelPrivilege);
			
		return FastResponse.create().errCode(0).subCode(0).errMsg("获取成功").obj(hashMap);
	}

	/**
	 * 我的个人信息/修改个人头像
	 * 
	 * @param userId
	 * @param headImage
	 * @return
	 * @throws IOException
	 * @throws JsonMappingException
	 * @throws JsonParseException
	 */
	@SuppressWarnings({ "deprecation", "unchecked" })
	@RequestMapping(value = "updateHeadImage")
	public ObjResponse<String> updateHeadPortrait(String userId, HttpServletRequest request)
			throws JsonParseException, JsonMappingException, IOException {
		String picRes = request.getParameter("picRes");
		Member member = new Member();
		member.setId(userId);
		member = memberService.get(member);
		picRes = picRes.replaceAll(".*\\[", "[").replaceAll("\\].*", "]");
		ObjectMapper mapper = new ObjectMapper();
		JavaType javaType = mapper.getTypeFactory().constructParametricType(List.class, UploadResultDto.class);
		List<UploadResultDto> uploadList = (List<UploadResultDto>) mapper.readValue(picRes, javaType);
		UploadResultDto urd = null;
		if (uploadList != null && uploadList.size() > 0)
			urd = uploadList.get(0);
		if (urd != null) {
			urd = uploadList.get(0);
			Album a = new Album();
			a.setAlbumSize(urd.getSize());
			a.setCategory(BasicApi.headImgCategory);
			a.setObjectId(Integer.parseInt(member.getId()));
			a.setOrginPath(urd.getPath());
			a.setThumbPath(urd.getThumb());
			a.setCreateBy(new User("0"));
			a.setFileName(urd.getName());
			a.setCreateDate(new Date());
			a.setUpdateBy(new User("0"));
			a.setUpdateDate(new Date());
			a.setDelFlag("0");
			int id = albumService.apiUpdateHeadImg(a);
			if(id == 0){
				albumService.apiInsert(a);				
			}
			member.setAvatar(urd.getThumb());
			memberService.save(member);
		}
		return FastResponse.create().errCode(0).subCode(1).errMsg("修改成功").obj("");
	}

	/**
	 * 我的个人信息/修改区域
	 * 
	 * @param userId
	 * @param area
	 * @return
	 */
	@RequestMapping(value = "updateDistrict")
	public ObjResponse<String> updateArea(String userId, String districtId) {
		String message = null;
		int errCode = 0;
		if(userId != null && !userId.equals("") && districtId != null && !districtId.equals("")){
			Member member = new Member();
			member.setId(userId);
			member = memberService.get(member);
			Area area = null, city = null, province = null;
			area = areaService.get(new Area(districtId));
			if(area != null){
				city = areaService.get(new Area(area.getParentId()));
				province = areaService.get(new Area(city.getParentId()));
				member.setAreaId(Integer.parseInt(districtId));
				member.setCityId(Integer.parseInt(city.getId()));
				member.setProviceId(Integer.parseInt(city.getParentId()));
				String district = province.getName()+city.getName()+area.getName();
				member.setDistrict(district); 
				memberService.save(member);
				message = "修改成功";
				errCode= 0;				
			}else{
				message = "修改失败，不存在该区域";
				errCode = 1;
			}

		}else{
			message = "修改失败，参数有误";
			errCode = 1;
		}

		return FastResponse.create().errCode(errCode).subCode(1).errMsg(message).obj("修改区域");
	}

	/**
	 * 我的个人信息/修改昵称
	 * 
	 * @param userId
	 * @param nickName
	 * @return
	 */
	@RequestMapping(value = "updateNickname")
	public ObjResponse<String> updateNickName(String userId, String nickname) {
		String message = null;
		int errCode = 0;
		if(userId != null && !userId.equals("") && nickname != null && !nickname.equals("")){
			Member member = new Member();
			member.setId(userId);
			member = memberService.get(member);
			member.setNikename(nickname);
			memberService.save(member);	
			message = "修改成功";
			errCode = 0;
		}else{
			message = "修改失败，参数有误";
			errCode = 1;
		}

		return FastResponse.create().errCode(errCode).subCode(1).errMsg(message).obj("修改昵称");
	}

}
